# coding=utf-8
from random import choice
import string
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from ContactsBook.models import *
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.core import serializers
from django.contrib import auth
from .data import grade_data
from django.core.mail import send_mail
import traceback
import json


def home(request):
    return render(request, 'index.html')


# @csrf_exempt
def signup(request):
    if request.method == 'GET':
        return render(request, 'signup.html')
    # new_my_user = None
    # state = None
    password = request.POST.get('password', '')
    repeat_password = request.POST.get('repeat_password', '')
    if password == '' or repeat_password == '':
        state = 'empty'
    elif password != repeat_password:
        state = 'repeat_error'
    else:
        username = request.POST.get('username', '')
        if User.objects.filter(username=username):
            state = 'username is taken, please check it or change your password'
        else:
            new_user = User.objects.create_user(username=username, password=password)
            new_user.save()
            new_my_user = Person(user=new_user, name=request.POST.get('name', ''), phone=request.POST.get('phone', ''),
                                 email=request.POST.get('email', ''), wechat=request.POST.get('wechat', ''))
            new_my_user.save()
            state = 'Dear '+username+', please login with your username'
            return render(request, 'success.html',{'method':u'注册','state':state})
            # return HttpResponse(json.dumps({
            #     'state': state,
            #     # 'user': new_my_user
            # }))
    return render(request, 'failure.html',{'method':u'注册','state':state})


@csrf_exempt
def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    user = auth.authenticate(username=username, password=password)

    if user is not None:
        auth.login(request, user)
        state = 'success'
        response=HttpResponse(json.dumps({'state': state}))
        response['Access-Control-Allow-Origin']='*'
        response['Access-Control-Allow-Methods']='GET,POST'
        return response
    else:
        state = 'not_exist_or_password_error'
    response=HttpResponse(json.dumps({'state': state}))
    response['Access-Control-Allow-Origin']='*'
    response['Access-Control-Allow-Methods']='GET,POST'
    return response


def logout(request):
    auth.logout(request)
    return HttpResponse(json.dumps({'state': 'logout_success'}))


@csrf_exempt
def getInfo(request):
    user = request.user if request.user.is_authenticated() else None
    if user is None:
        return HttpResponse(json.dumps({'state': 'not_login'}))
    persons = Person.objects.filter(user=user)
    # person=persons[0] if persons.count()>0 else None
    return HttpResponse(serializers.serialize('json', persons))


@csrf_exempt
def groupList(request):
    user = request.user if request.user.is_authenticated() else None
    if user is None:
        return HttpResponse(json.dumps({'state': 'not_login'}))
    # print(user.username)
    person = Person.objects.filter(user=user)[0]
    groupL = person.rel.all()
    return HttpResponse(serializers.serialize('json', groupL))

@csrf_exempt
def getGradeClassList(request):
    user = request.user if request.user.is_authenticated() else None
    if user is None:
        return HttpResponse(json.dumps({'state': 'not_login'}))
    # print(user.username)
    person = Person.objects.filter(user=user)[0]
    groupL = person.grade_class_list.all()
    return HttpResponse(serializers.serialize('json', groupL))

@csrf_exempt
def getMemberGroup(request):
    if request.method == 'GET':
        return render(request, 'getmember.html')
    user = request.user if request.user.is_authenticated() else None
    if user is None:
        return HttpResponse(json.dumps({'state': 'not_login'}))
    groupID = request.POST.get('group', '')
    groups = Organization.objects.filter(id=groupID)
    group = groups[0] if groups.count() > 0 else None
    if group == None:
        return HttpResponse(json.dumps({'state': 'group_not_exist'}))
    return HttpResponse(serializers.serialize('json', group.person_set.all()))

@csrf_exempt
def getMemberGradeClass(request):
    if request.method == 'GET':
        return render(request, 'getmembergradeclass.html')
    user = request.user if request.user.is_authenticated() else None
    if user is None:
        return HttpResponse(json.dumps({'state': 'not_login'}))
    try:
        gradeName = request.POST.get('grade', '')
        className=request.POST.get('class', '')
        grade_class=GradeClass.objects.filter(gradename=gradeName,classname=className)[0]
        return HttpResponse(serializers.serialize('json', grade_class.person_set.all()))
    except Exception as e:
        return HttpResponse(json.dumps({'state': 'grade_class_not_exist'}))

@csrf_exempt
def getAdminMember(request):
    user = request.user if request.user.is_authenticated() else None
    if user is None:
        return HttpResponse(json.dumps({'state': 'not_login'}))
    try:
        memberList=Person.objects.filter(is_super=True)
        return HttpResponse(serializers.serialize('json', memberList))
    except Exception as e:
        return HttpResponse(json.dumps({'state': 'not_exist'}))
    # groupID = request.POST.get('group', '')
    # groups = Organization.objects.filter(id=groupID)
    # group = groups[0] if groups.count() > 0 else None
    # if group == None:
    #     return HttpResponse(json.dumps({'state': 'group_not_exist'}))
    # return HttpResponse(serializers.serialize('json', group.person_set.all()))

def getGradeClass(request):
    user = request.user if request.user.is_authenticated() else None
    if user is None:
        return HttpResponse(json.dumps({'state': 'not_login'}))
    return HttpResponse(json.dumps(grade_data))
#
# def getClassGroup(request):
#     if request.method == 'GET':
#         return render(request, 'getmember.html')
#     user = request.user if request.user.is_authenticated() else None
#     if user is None:
#         return HttpResponse(json.dumps({'state': 'not_login'}))
#     groupID = request.POST.get('group', '')
#     groups = Organization.objects.filter(id=groupID)
#     group = groups[0] if groups.count() > 0 else None
#     if group == None:
#         return HttpResponse(json.dumps({'state': 'group_not_exist'}))
#     return HttpResponse(serializers.serialize('json', group.person_set.all()))


@csrf_exempt
def joinGroup(request):
    if request.method == 'GET':
        return render(request, 'joingroup.html')
    user = request.user if request.user.is_authenticated() else None
    if user is None:
        return HttpResponse(json.dumps({'state': 'not_login'}))
    groupID = request.POST.get('group', '')
    groups = Organization.objects.filter(id=groupID)
    group = groups[0] if groups.count() > 0 else None
    if group == None:
        return HttpResponse(json.dumps({'state': 'group_not_exist'}))
    persons = Person.objects.filter(user=user)
    person = persons[0] if persons.count() > 0 else None
    if person is not None:
        person.rel.add(group)
        person.save()
        return HttpResponse(json.dumps({'state': 'join_group_success'}))
    else:
        return HttpResponse(json.dumps({'state': 'join_group_fail'}))


@csrf_exempt
def addFriend(request):
    if request.method == 'GET':
        return render(request, 'addfriend.html')
    user = request.user if request.user.is_authenticated() else None
    if user is None:
        return HttpResponse(json.dumps({'state': 'not_login'}))
    friendID = request.POST.get('friend', '')
    friends = Person.objects.filter(id=friendID)
    friend = friends[0] if friends.count() > 0 else None
    if friend == None:
        return HttpResponse(json.dumps({'state': 'user_not_exist'}))
    persons = Person.objects.filter(user=user)
    person = persons[0] if persons.count() > 0 else None
    if person is not None:
        person.friends.add(friend)
        person.save()
        return HttpResponse(json.dumps({'state': 'add_friend_success'}))
    else:
        return HttpResponse(json.dumps({'state': 'add_friend_fail'}))


# @csrf_exempt
def getFriends(request):
    user = request.user if request.user.is_authenticated() else None
    if user is None:
        return HttpResponse(json.dumps({'state': 'not_login'}))
    persons = Person.objects.filter(user=user)
    person = persons[0] if persons.count() > 0 else None
    if person is not None:
        return HttpResponse(serializers.serialize('json', person.friends.all()))
    else:
        return HttpResponse(json.dumps({'state': 'user_not_exist'}))


@csrf_exempt
def createGroup(request):
    if request.method == 'GET':
        return render(request, 'creategroup.html')
    user = request.user if request.user.is_authenticated() else None
    if user is None:
        return HttpResponse(json.dumps({'state': 'not_login'}))
    try:
        groupName = request.POST.get('name', '')
        groupIntro = request.POST.get('intro', '')
        group = Organization(name=groupName, introduction=groupIntro)
        group.save()
        return HttpResponse(json.dumps({'state': 'create_success'}))
    except Exception as e:
        return HttpResponse(json.dumps({'state': 'create_fail'}))


@csrf_exempt
def searchGroup(request):
    if request.method == 'GET':
        return render(request, 'searchgroup.html')
    user = request.user if request.user.is_authenticated() else None
    if user is None:
        return HttpResponse(json.dumps({'state': 'not_login'}))
    try:
        groupName = request.POST.get('group', '')
        groups = Organization.objects.filter(name__icontains=groupName).all()
        return HttpResponse(serializers.serialize('json', groups))
    except Exception as e:
        return HttpResponse(json.dumps({'state': 'search_fail'}))


@csrf_exempt
def searchPerson(request):
    if request.method == 'GET':
        return render(request, 'searchperson.html')
    user = request.user if request.user.is_authenticated() else None
    if user is None:
        return HttpResponse(json.dumps({'state': 'not_login'}))
    try:
        searchValue = request.POST.get('person', '')
        persons1 = Person.objects.filter(name__icontains=searchValue).all()
        persons2 = Person.objects.filter(phone__icontains=searchValue).all()
        persons = persons1 | persons2;
        persons = persons.distinct()
        return HttpResponse(serializers.serialize('json', persons))
    except Exception as e:
        return HttpResponse(json.dumps({'state': 'search_fail'}))

@csrf_exempt
def addGradeClass(request):
    if request.method == 'GET':
        return render(request, 'addgradeclass.html')
    user = request.user if request.user.is_authenticated() else None
    if user is None:
        return HttpResponse(json.dumps({'state': 'not_login'}))
    try:
        gradeName = request.POST.get('grade', '')
        className=request.POST.get('class', '')
        grade_class=GradeClass.objects.filter(gradename=gradeName,classname=className)[0]
        person = Person.objects.filter(user=user)[0]
        person.grade_class_list.add(grade_class)
        person.save()
        return HttpResponse(json.dumps({'state': 'add_grade_class_success'}))
    except Exception as e:
        return HttpResponse(json.dumps({'state': 'add_grade_class_fail'}))

def MakePass(length=8, chars=string.letters+string.digits):
    return ''.join([choice(chars) for i in range(length)])

@csrf_exempt
def forgetPassword(request):
    if request.method == 'GET':
        return render(request, 'forgetpassword.html')
    try:
        email=request.POST.get('email', '')
        user=Person.objects.filter(email=email)
        assert len(user)==1
        user=user[0]
        randompassword=MakePass(8)
        user.user.set_password(randompassword)
        user.user.save()
        user.save()
        send_mail(u'校友商邦密码修改通知','Dear '+user.user.username+', new password is: '+randompassword+' \nplease login with new password and change it.', 'healthwuhan@163.com',[user.email], fail_silently=False)
        return HttpResponse(json.dumps({'state': u'Password has been sent to your email.'}))
    except Exception as e:
        traceback.print_exc()
        return HttpResponse(json.dumps({'state': 'change_password_fail'}))

@csrf_exempt
def createTeam(request):
    if request.method == 'GET':
        return render(request, 'createteam.html')
    try:
        name=request.POST.get('name')
        vocation=request.POST.get('vocation')
        area=request.POST.get('area')
        team_code=request.POST.get('team_code','')
        team=Team(name=name,vocation=vocation,area=area,team_code=team_code)
        team.save()
        return render(request, 'success.html',{'method':u'创建团队'})
    except Exception as e:
        traceback.print_exc()
        return render(request, 'failure.html',{'method':u'创建团队'})

@csrf_exempt
def createTeam(request):
    if request.method == 'GET':
        return render(request, 'createteam.html')
    try:
        name=request.POST.get('name')
        vocation=request.POST.get('vocation')
        area=request.POST.get('area')
        team_code=request.POST.get('team_code','')
        team=Team(name=name,vocation=vocation,area=area,team_code=team_code)
        team.save()
        return render(request, 'success.html',{'method':u'创建团队'})
    except Exception as e:
        traceback.print_exc()
        return render(request, 'failure.html',{'method':u'创建团队'})

@csrf_exempt
def joinTeam(request):
    if request.method == 'GET':
        return render(request, 'jointeam.html')
    try:
        id=request.POST.get('id')
        user = request.user if request.user.is_authenticated() else None
        if user is None:
            return render(request, 'failure.html',{'method':u'加入团队','state':u'尚未登录！'})
        person = Person.objects.filter(user=user)[0]
        team=Team.objects.filter(id=id)
        if len(team)==1:
            team=team[0]
        else:
            return render(request, 'failure.html',{'method':u'加入团队','state':u'团队不存在'})
        person.team_list.add(team)
        person.save()
        return render(request, 'success.html',{'method':u'加入团队'})
    except Exception as e:
        traceback.print_exc()
        return render(request, 'failure.html',{'method':u'加入团队'})